import axios from 'axios';
import { baseURL, timeout, headers } from '../config/api';

// 检查是否在HBuilder环境中
const isHBuilder = () => {
    return window.plus && window.plus.net;
};

// 获取API基础URL
const getBaseURL = () => {
    console.log('当前API地址:', baseURL);
    return baseURL;
};

// 创建 axios 实例
const instance = axios.create({
    baseURL: getBaseURL(),
    timeout,
    headers,
    withCredentials: false
});

// 统一的请求处理函数
const handleRequest = async (config) => {
    // 确保baseURL存在
    config.baseURL = getBaseURL();
    
    // 从 localStorage 获取 token
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    if (userInfo.token) {
        config.headers['Authorization'] = `Bearer ${userInfo.token}`;
    }

    // 在HBuilder环境中使用XMLHttpRequest
    if (isHBuilder()) {
        return new Promise((resolve, reject) => {
            const xhr = new plus.net.XMLHttpRequest();
            const fullUrl = `${config.baseURL}${config.url}`;
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        try {
                            const data = JSON.parse(xhr.responseText);
                            resolve({ data });
                        } catch (e) {
                            reject({
                                response: {
                                    data: {
                                        success: false,
                                        message: '解析响应数据失败'
                                    },
                                    status: 500
                                }
                            });
                        }
                    } else {
                        try {
                            const errorData = JSON.parse(xhr.responseText);
                            reject({
                                response: {
                                    data: errorData,
                                    status: xhr.status
                                }
                            });
                        } catch (e) {
                            reject({
                                response: {
                                    data: {
                                        success: false,
                                        message: `请求失败: ${xhr.status}`
                                    },
                                    status: xhr.status
                                }
                            });
                        }
                    }
                }
            };

            xhr.onerror = () => reject({
                response: {
                    data: {
                        success: false,
                        message: '网络请求失败'
                    },
                    status: 500
                }
            });

            try {
                xhr.open(config.method || 'get', fullUrl, true);
                
                // 设置请求头
                if (config.headers) {
                    Object.keys(config.headers).forEach(key => {
                        xhr.setRequestHeader(key, config.headers[key]);
                    });
                }
                
                // 发送请求
                if (config.data) {
                    xhr.send(JSON.stringify(config.data));
                } else {
                    xhr.send(null);
                }
            } catch (e) {
                reject({
                    response: {
                        data: {
                            success: false,
                            message: '请求发送失败'
                        },
                        status: 500
                    }
                });
            }
        });
    }

    // 非HBuilder环境使用axios
    return instance(config);
};

// 创建请求方法
const request = {
    get: (url, params, config = {}) => {
        return handleRequest({
            ...config,
            method: 'get',
            url,
            params
        });
    },
    post: (url, data, config = {}) => {
        return handleRequest({
            ...config,
            method: 'post',
            url,
            data
        });
    },
    put: (url, data, config = {}) => {
        return handleRequest({
            ...config,
            method: 'put',
            url,
            data
        });
    },
    delete: (url, config = {}) => {
        return handleRequest({
            ...config,
            method: 'delete',
            url
        });
    }
};

export default request; 